package com.jc.service.api.yx163;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.ExceptionUtil;
import com.jc.common.util.HttpUtil;
import com.jc.common.util.JcStringUtil;
import com.jc.common.util.MD5;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.LogType;
import com.jc.framework.util.PropertyPlaceholder;
import com.jc.framework.util.SpringUtils;
import com.jc.service.api.ProductCheckAdapter;
import com.jc.service.model.yx.YanXuanResult;
import com.jc.service.systemloglist.SystemLogListService;


public abstract class YanXuanAdapter  extends ProductCheckAdapter {
	
	private final Logger LOGGER = LoggerFactory.getLogger(YanXuanAdapter.class);
	private String appKey = (String)PropertyPlaceholder.getProperty("yx.163.appKey");
	private String appSecret = (String)PropertyPlaceholder.getProperty("yx.163.appSecret");
	private String url = (String)PropertyPlaceholder.getProperty("yx.163.url");
	private String timestamp = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
	private SystemLogListService systemLogListService = SpringUtils.getBean(SystemLogListService.class);
	
	 
	public LinkedHashMap<String,Object> getSign(LinkedHashMap<String, Object> map) {
		timestamp = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
		if(map == null || map.get("method") == null ||StringUtils.isBlank(map.get("method").toString())) {
			throw new BaseServiceException("获取网易严选API签名,必须传入 method");
		}
		map.put("appKey", appKey);
		map.put("timestamp", timestamp);		
		//这里将map.entrySet()转换成list
        List<Map.Entry<String,Object>> list = new ArrayList<Map.Entry<String,Object>>(map.entrySet());
        //然后通过比较器来实现排序
        Collections.sort(list,new Comparator<Map.Entry<String,Object>>() {
            //升序排序
            public int compare(Entry<String, Object> o1,Entry<String, Object> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
		StringBuffer buffer = new StringBuffer();
		buffer.append(appSecret);
		if(list != null && list.size() > 0) {
			for(Map.Entry<String,Object> entry : list){ 
				buffer.append(entry.getKey() + "=" + entry.getValue());
	        }
		}
		
		buffer.append(appSecret);
		LOGGER.error("加密前字符串" + buffer.toString());
		map.put("sign", MD5.md5(buffer.toString()));
		LOGGER.error("加密后字符串" + MD5.md5(buffer.toString()));
		return map;
	}
	
	
//	public List<Object> postYanXuan(LinkedHashMap<String,Object> params) {
//		String ret = null;
//		LogType lt = null;
//		List<Object> result = new ArrayList<Object>();
//		try {
//			lt = (LogType)params.get("logType");
//			if(lt == null) {
//				throw new BaseServiceException("请求网易严选接口缺少日志类型");
//			}
//			ret = HttpUtil.post(url, params);
//			JSONObject retObject = JSONObject.parseObject(ret);
//			if(retObject != null) {
//				if(HttpStatus.OK.value() == retObject.getInteger("code")) {
//					JSONArray objectArray = retObject.getJSONArray("result");
//					for(int i = 0 ; objectArray != null && i < objectArray.size() ; i++) {
//						result.add(objectArray.get(i));
//					}
//					systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.OK, "", lt , ret);
//				}else {
//					systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.FAIL, "", lt , ret);
//				}
//			}else {
//				systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.FAIL, "网易返回值转换的对象为空", lt , ret);
//			}
//			return result;
//		} catch (Exception e) {
//			systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 150), lt , ret);
//			LOGGER.error("和网易严选交互错误 : 详细信息 , {},{}" ,e.getMessage(),e);
//			return result;
//		}
//		
//	}
	
	
	
	public YanXuanResult postYanXuan(LinkedHashMap<String,Object> params) {
		String ret = null;
		LogType lt = null;
		List<Object> resultObjectList = new ArrayList<Object>();
		YanXuanResult retMap = new YanXuanResult();
		try {
			lt = (LogType)params.get("logType");
			if(lt == null) {
				throw new BaseServiceException("请求网易严选接口缺少日志类型");
			}


			if(params.get("url") != null) {
				url = (String)params.get("url");
			}else {
				url = (String)PropertyPlaceholder.getProperty("yx.163.url");
			}
			ret = HttpUtil.post(url, params );
			
			LOGGER.error("请求网易严选接口:--------------  url : {} ,     参数: {}     ,    返回值:  {}" , url, JSONObject.toJSONString(params) , ret );
			
			
			JSONObject retObject = JSONObject.parseObject(ret);
			
			if(retObject != null) {
				if(retObject.getInteger("code") == null) {
					systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.FAIL, "", lt , ret);
					retMap.setCode(1711);
					retMap.setMessage(retObject.getString("msg"));
					return retMap;
				}
				if(HttpStatus.OK.value() == retObject.getInteger("code")) {
					JSONArray objectArray = null;
					try {
						objectArray = retObject.getJSONArray("result");
					}catch (Exception e) {
						
						if(StringUtils.isNotBlank(retObject.getString("result"))) {
							if(JcStringUtil.isJSONValid(retObject.getString("result"))) {
								resultObjectList.add(JSON.parseObject(retObject.getString("result")));
							}else {
								resultObjectList.add(retObject.getString("result"));
							}
						}
					}
					
					for(int i = 0 ; objectArray != null && i < objectArray.size() ; i++) {
						resultObjectList.add(objectArray.get(i));
					}
					
					retMap.setCode(200);
					retMap.setResult(resultObjectList);
					systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.OK, "", lt , ret);
					return retMap;
					
				}else {
					retMap.setCode(retObject.getInteger("code"));
					retMap.setMessage(retObject.getString("msg"));
					systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.FAIL, "", lt , ret);
					return retMap;
				}
			}else {
				retMap.setCode(1711);
				retMap.setMessage("网易严选的返回值转换为JSON后为空");
				systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.FAIL, "网易返回值转换的对象为空", lt , ret);
				return retMap;
			}
		} catch (Exception e) {
			systemLogListService.addSystemLog(JSONObject.toJSONString(params), Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 150), lt , ret);
			LOGGER.error("和网易严选交互错误 : 详细信息 , {},{}" ,e.getMessage(),e);
			
			retMap.setCode(1711);
			retMap.setMessage(ExceptionUtil.subExceptionMessage(e, 0, 150));
			
			return retMap;
		}
		
	}
	
	
	
	
	
}
